package com.white.hot.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import okhttp3.MediaType;
import okhttp3.Request;
import okio.BufferedSink;

import org.apache.http.client.methods.HttpPost;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.google.gson.Gson;
import com.sun.xml.internal.rngom.parse.host.Base;
import com.white.hot.dto.resp.BaseResp;
import com.white.hot.utils.OkHttpManager;
import com.white.hot.utils.TextUtils;
import com.white.hot.utils.OkHttpManager.ResultCallback;


@Controller
@RequestMapping("/msg")
public class MsgController extends BaseController
{
	
	private final String appKey = "1bd45d0135814";
	private final String url = "https://webapi.sms.mob.com/sms/verify";
	private OkHttpManager manager;
	
	@RequestMapping("/varify")
	private void varify(
			@RequestParam("phone") String phone,
			@RequestParam("zone") String zone,
			@RequestParam("code") String code,
			HttpServletRequest request, final HttpServletResponse response)
	{
		manager = OkHttpManager.getInstance();
		if(TextUtils.isEmpty(phone) || TextUtils.isEmpty(zone) || TextUtils.isEmpty(code))
		{
			BaseResp br = buildParamIncompleteResp(new BaseResp());
			Gson gson = new Gson();
			String content = gson.toJson(br);
			writeResponse(response, content);
		}else
		{
			Map<String ,String> param = new HashMap<String,String>();
			param.put("appkey", appKey);
			param.put("phone", phone);
			param.put("zone", zone);
			param.put("code", code);
			manager.doPost(url, new ResultCallback<String>()
			{

				@Override
				public void onError(String simpleMsg, Exception e)
				{
					BaseResp br = buildInnerErrorResp(new BaseResp());
					br.setInfo(simpleMsg);
					Gson gson = new Gson();
					String content = gson.toJson(br);
					writeResponse(response, content);
				}

				@Override
				public void onSuccess(String result)
				{
					BaseResp br = buildSuccessResp(new BaseResp());
					br.setInfo(result);
					Gson gson = new Gson();
					String content = gson.toJson(br);
					writeResponse(response, content);
				}
			}, param);
		}
	}
	
	private void writeResponse(HttpServletResponse response,String content)
	{
		PrintWriter  w = null;
		try
		{
			response.setCharacterEncoding("UTF-8");
			w = response.getWriter();
			w.write(content);
			w.flush();
		} catch (IOException e)
		{
			e.printStackTrace();
		}finally
		{
			if(w != null)
			{
				w.close();
			}
		}
	}
}
